package excel

import (
	"github.com/xuri/excelize/v2"
)

// 新建
func New() *xlsx {
	f := excelize.NewFile()
	x := &xlsx{
		f:            f,
		active_name:  "Sheet1",
		active_index: 1,
		index_name:   map[int]string{},
		name_index:   map[string]int{},
	}
	x.index_name[x.active_index] = x.active_name
	x.name_index[x.active_name] = x.active_index

	return x
}

// 打开
func Open(filename string) (*xlsx, error) {
	f, e := excelize.OpenFile(filename)
	if e != nil {
		return nil, e
	}

	x := &xlsx{
		f:          f,
		index_name: map[int]string{},
		name_index: map[string]int{},
	}

	for active_index, active_name := range x.GetAllSheet() {
		x.active_index = active_index
		x.active_name = active_name
		x.index_name[active_index] = active_name
		x.name_index[active_name] = active_index
	}

	return x, nil
}

// 保存
func (x *xlsx) SaveAs(filename string) error {
	e := x.f.SaveAs(filename)
	if e != nil {
		return e
	}
	return nil
}
